<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <!-- style="width: 150px;margin-right:15px;" -->
      <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px"
            :style="{ width: inputWid(param.scanWorkOrderNo) }"
            v-model="param.scanWorkOrderNo"
            placeholder="请输入工单"
        ></el-input>
        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px"
            :style="{ width: inputWid(param.scanOrderType) }"
            v-model="param.scanOrderType"
            placeholder="请输入单别"
        ></el-input>
        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px"
            :style="{ width: inputWid(param.scanProduceNo) }"
            v-model="param.scanProduceNo"
            placeholder="请输入品号"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px"
            :style="{ width: inputWid(param.sectionNo) }"
            v-model="param.sectionNo"
            placeholder="请输入工段编号"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px"
            :style="{ width: inputWid(param.deviceBarcode) }"
            v-model="param.deviceBarcode"
            placeholder="输入工序条码"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="width: 150px;margin-right:15px;"
            v-model="param.jobNumber"
            placeholder="请输入员工工号"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="width: 150px;margin-right:15px;margin-top: 10px"
            v-model="param.money"
            placeholder="金额"
            v-if="userInfo.account == 'lishali' || userInfo.roleId == 14 || userInfo.roleId == 44"
        ></el-input>
        
        <el-date-picker
          v-model="dateOptions"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          style="margin-right:15px;">
        </el-date-picker>

        <el-button type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
        <el-button
            type="button"
            v-waves
            class="el-button el-button--warning"
            @click="cancelSubmit"
        >
        取消</el-button>
        <el-button class="filter-item"
        style="margin-top:10px"
        :loading="btnLoading"
        type="primary"
        v-waves
        @click="updBacthMonty"
        v-if="userInfo.account == 'lishali' || userInfo.roleId == 14 || userInfo.roleId == 44">刷新全部</el-button>
    
    </div>

    <!-- table 表格 -->
    <el-table  :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
      <!-- <el-table-column  label="序号" type="index" align="center" width="80px"/> -->
      
      <el-table-column label="员工工号"  prop="jobNumberStr" align="center"/>
      <el-table-column label="条码"  prop="deviceBarcode" align="center"/>
      <el-table-column label="sop号"  prop="sopBarcode" align="center"/>
      <el-table-column label="产品号"  prop="scanProduceNo" align="center"/>
      <el-table-column label="工单单别"  prop="scanOrderType" align="center"/>
      <el-table-column label="工单单号"  prop="scanWorkOrderNo" align="center"/>
      <el-table-column label="工序名称"  prop="scanProcessName" align="center"/>
      <el-table-column label="扫码时间"  prop="scanTime" align="center" width="140"/>
      <el-table-column label="标准工时"  prop="standardManTime" align="center"/>
      <el-table-column label="排产序号"  prop="planNo" align="center"/> 
      <el-table-column label="状态" prop="isDelete" align="center">
        <template slot-scope="scope"> 
          <div class="fx">
            {{
              scope.row.isDelete == 0
                ? '未删除'
                : "已删除"
            }}
           </div>
        </template>
      </el-table-column>
      <el-table-column label="金额"  prop="money" align="center" v-if="userInfo.account == 'lishali' || userInfo.roleId == 14 || userInfo.roleId == 44"/>
      <el-table-column label="操作" fixed="right" align="center" v-if="userInfo.account == 'lishali' || userInfo.roleId == 14 || userInfo.roleId == 24 || userInfo.roleId == 44">
            <template slot-scope="scope" >
                <div class="fx" style="display: flex">
                  <el-button size="mini"
                  type="primary"
                  v-waves
                  :loading="scope.row.updateMoney"
                  @click="submitupdate(scope.row,scope.$index)"
                  v-if="userInfo.account == 'lishali' || userInfo.roleId == 14 || userInfo.roleId == 44">刷新工资
                </el-button>
                <el-button
                    icon="el-icon-delete"
                    class="el-button el-button--danger"
                    style="font-size: 15px;"
                    @click="handleDelete(scope.row,scope.$index)"
                ></el-button>
                </div>
            </template>
        </el-table-column>
    </el-table>
   
   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>

    <el-form :inline="true" style="width: 100%">
      <el-form-item>
        <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>
      </el-form-item>
      <el-form-item>
        <el-input v-model.number="outputNum" placeholder="导出数量" style="width: 100px" @input="inputOutputNum"></el-input>
      </el-form-item>
    </el-form>

    <el-dialog title="换算规则以及结果" :visible.sync="showRulesAndresult" width="600px">

      <el-divider content-position="left">公式：</el-divider>
      <el-link type="primary" :underline="false">{{this.getValueName(moneyProgramme.moneyFormulaStr)}}</el-link>
      <el-divider content-position="left">换算过程和结果(金额)：</el-divider>
      <el-link type="primary" :underline="false">{{this.getValueData(moneyProgramme.moneyFormulaStr) + '='}}{{moneyProgramme.scanInfo?moneyProgramme.scanInfo.money:0}}</el-link>
      <div class="errorBtn" style="margin-top: 10px">
          <!-- <el-button type="warning" @click="showRulesAndresult = false">取消</el-button> -->
          <el-button type="primary" @click="isSure">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择删除类型" :visible.sync="delShow" center width="20%">
      <el-radio v-model="delValue" size="medium" label="1">按条码删除</el-radio>
      <el-radio v-model="delValue" size="medium" label="2">按工单删除</el-radio>
      <!-- <el-link type="danger" :underline="false">注意：这将会永久删除该行数据</el-link> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="delShow = false">取 消</el-button>
        <el-button type="primary" @click="scanInfoRemove" :loading="delLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { findMachineScanInfo,scanInfoRemove,singleMonty_ems_zp,bacthMonty_ems_zp } from '../../api/staffscan'
import { getCenter } from '../../api/workSection.js'

export default {
    name: 'emsScanRecords',
    data () {
        return {
          delValue: '',
          itemObj:{},
          delShow: false,
          btnLoading: false,
          delLoading: false,
          showRulesAndresult: false,
          moneyProgramme: {},
          userInfo: this.$store.state.user.userInfo,
            listQuery: {
                page: 1,                                    //页码
                limit: 10,                                   //每页多少条记录
                workCenter: 'EMS总装车间'
            },
            param: {
                deviceBarcode: '',                      //工序条码
                jobNumber: '',                           //员工工号
                date: this.setMonth(),                                //日期
            },
            total: 0,                                      //数据的总数
            tableInfo: [],
            loadingList: false,
            loading: false,
            dateOptions: this.getNowTime(),
            pickerOptions: {
              shortcuts: [{
                text: '最近一周',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '最近一个月',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '最近三个月',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                  picker.$emit('pick', [start, end]);
                }
              }]
            },
            paramNameLists: [{name:'装配零件数量',value:'ZP_LJSL'},
            {name:'装配普通螺钉数量',value:'ZP_LDSL'},
            {name:'装配外购件数量',value:'ZP_WGJSL'},
            {name:'装配打胶长度',value:'ZP_DJCD'},
            {name:'装配不锈钢螺钉数量',value:'ZP_BXGLDSL'},
            {name:'装配功率螺钉数量',value:'ZP_GLLDSL'},
            {name:'单件重量',value:'DJZL'},
            {name:'单价1',value:'DJ1'},
            {name:'单价2',value:'DJ2'},
            {name:'单价3',value:'DJ3'},
            {name:'单价',value:'DJ'},
            {name:'难度系数',value:'NDXS'},
            {name:'散单系数',value:'SDXS'},
            {name:'定额人数',value:'DERS'},
            {name:'加工数量',value:'JGSL'},
            {name:'加工次数',value:'JGCS'},
            {name:'铆钉数量',value:'MDSL'},
            {name:'折弯刀数',value:'ZWDS'},
            {name:'单位平方',value:'DWPF'},
            {name:'连焊长度',value:'LHCD'},
            {name:'碰焊点数',value:'PHDS'},
            {name:'加工周长',value:'JGZC'},
            {name:'焊点数量',value:'HDSL'},
            {name:'扫码人数',value:'SCANLIMIT'},
            {name:'EMS装配计件',value:'EMS_ZPJJ'},
            {name:'EMS系数类型',value:'EMS_XXLS'},
          ],
          outputNum: ''
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '120px'
            } else {
              return (120 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
      inputOutputNum(){
          console.log(this.outputNum)
          if(this.outputNum>50000){
            this.outputNum = ''
            this.$message.error('导出数量不能超过50000!')
          }
        },
      // 刷新全部工资
      async updBacthMonty(){
          this.btnLoading = true
          setTimeout(() => {
            this.btnLoading = false
          }, 120000);
          // let query = {}
          let query = Object.assign({},this.param)
          // if(!this.dateOptions.length) return this.$message.error('日期范围不能为空')
          if(this.dateOptions == null || !this.dateOptions.length)  {
            this.$message.error('日期范围不能为空')
            this.btnLoading = false
            return
          }
          delete query.date
          query.strTime = this.dateOptions[0]
          query.endTime = this.dateOptions[1]
          let data = await bacthMonty_ems_zp(query)
          if(data.code == '500') return
          if(data.code != '1') return this.$message.error(data.msg)
          this.btnLoading = false
        },
      getValueName(key){
          let name = key
          this.paramNameLists.forEach((item,index) => {
              if(name && name.includes('DJZL')){
                let reg = new RegExp('DJZL','g')
                name = name.replace(reg,'单价重量')
              }else if(name && name.includes('ZP_DJCD')){
                let reg = new RegExp('ZP_DJCD','g')
                name = name.replace(reg,'装配打胶长度')
              }else if(name && name.includes('DJ')){
                let reg = new RegExp('DJ','g')
                name = name.replace(reg,'单价')
              }else if(name && name.includes(item.value)){
                let reg = new RegExp(item.value,'g')
                name = name.replace(reg,item.name)
            }
          })
          return name
        },
        getValueData(key){
          console.log(this.moneyProgramme.moneyFormulaMap);
          let data = key
          for (let key in this.moneyProgramme.moneyFormulaMap) {
            if(data && data.includes('DJZL')){
              let reg = new RegExp('DJZL','g')
              data = data.replace(reg,this.moneyProgramme.moneyFormulaMap.DJZL)
            }
            if(data && data.includes('ZP_DJCD')){
              let reg = new RegExp('ZP_DJCD','g')
              data = data.replace(reg,this.moneyProgramme.moneyFormulaMap.ZP_DJCD)
            }
            if(data && data.includes('DJ')){
              let reg = new RegExp('DJ','g')
              data = data.replace(reg,this.moneyProgramme.moneyFormulaMap.DJ)
            }
            let reg = new RegExp(key,'g')
            data = data.replace(reg,this.moneyProgramme.moneyFormulaMap[key])
            console.log(data);
          }
          // this.paramNameLists.forEach((item,index) => {
          //   if(data && data.includes('DJZL')){
          //       let reg = new RegExp('DJZL','g')
          //       data = data.replace(reg,'单价重量')
          //     }else if(data && data.includes('ZP_DJCD')){
          //       let reg = new RegExp('ZP_DJCD','g')
          //       data = data.replace(reg,'装配打胶长度')
          //     }else if(data && data.includes('DJ')){
          //       let reg = new RegExp('DJ','g')
          //       data = data.replace(reg,'单价')
          //     }else if(data && data.includes(item.value)){
          //     // this.moneyProgramme.moneyFormulaMap[item.value]
          //     let reg = new RegExp(item.value,'g')
          //     let dataValue = this.moneyProgramme.moneyFormulaMap[item.value]
          //     console.log('22',dataValue);
          //     console.log(this.moneyProgramme.moneyFormulaMap);
          //     data = data.replace(reg,dataValue)
          //     console.log(data);
          //   }
          // })
          return data
        },
        isSure(){
          this.showRulesAndresult = false
          this.handleFilter()
        },
      async submitupdate(row,index){
          this.tableInfo[index].updateMoney = true
          setTimeout(() => {
            this.tableInfo[index].updateMoney = false
          }, 120000);
          const set = new URLSearchParams(row.deviceBarcode);
          console.log('11',row.deviceBarcode);
          console.log('11',set);
          let data = await singleMonty_ems_zp({deviceBarcode: row.deviceBarcode,sopBarcode: row.sopBarcode,scanTime: row.scanTime})
          if(data.code == '500') return
          if(data.code != '1') return this.$message.error(data.msg)
          this.$message.success(data.msg)
          if(!data.data.moneyFormulaStr) return
          this.showRulesAndresult = true
          this.moneyProgramme = data.data
        },
        getData(){
          console.log(1)
          this.listQuery.page = 1
          this.listQuery.limit = 10
          this.handleFilter()
        },
        async handleFilter() {
            this.loadingList = true
            let query = Object.assign({},this.listQuery)
            if(this.param.deviceBarcode){ query.deviceBarcode = this.param.deviceBarcode}
            if(this.param.jobNumber){ query.jobNumber = this.param.jobNumber}
            if(this.param.sectionNo){ query.sectionNo = this.param.sectionNo}
            if(this.param.scanWorkOrderNo){ query.scanWorkOrderNo = this.param.scanWorkOrderNo}
            if(this.param.scanOrderType){ query.scanOrderType = this.param.scanOrderType}
            if(this.param.scanProduceNo){ query.scanProduceNo = this.param.scanProduceNo}
            if(this.param.money){ query.money = this.param.money}
            if(this.dateOptions) {
              if(this.dateOptions.length) {
                  query.strTime = this.dateOptions[0]
                  query.endTime = this.dateOptions[1]
              }
            }
            let data = await findMachineScanInfo(query)
            let errmsg = data.msg
            if(data.code == '1'){
                this.total = data.data.count
                this.tableInfo = data.data.list
                this.loadingList = false
                if(!this.tableInfo.length) return
                this.tableInfo.forEach(item=>{
                  let jobNumberStr = []
                  if(item.jobNumber) { jobNumberStr.push(item.jobNumber) }
                  if(item.jobNumber2) { jobNumberStr.push(item.jobNumber2) }
                  if(item.jobNumber3) { jobNumberStr.push(item.jobNumber3) }
                  item.jobNumberStr = jobNumberStr.join(',')
                  console.log('tableInfo',item.jobNumberStr,item.jobNmuber,)
                })
            } else {
                this.$message({
                    message: errmsg,
                    type: 'warning'
                })
            }
            this.loadingList = false
        },
        handleDelete(row,index) {
          this.itemObj = row
          this.delShow = true
        },
        async scanInfoRemove(){
          if(!this.delValue) return this.$message.error('请选择删除类型！')
          let query = {
            deviceBarcode:this.itemObj.deviceBarcode,
            planNo:this.itemObj.planNo,
          }
          if(this.delValue == 1){
            query.removeType = 'sn'
          }else{
            query.removeType = 'planNo'
          }
          this.delLoading = true
          let res = await scanInfoRemove(query)
          this.delLoading = false
          if(res.code != '1') return this.$message.error(res.msg)
          this.$message.success(res.msg)
          this.delShow = false
          this.handleFilter()
        },
        // table表单下方的页码组件改变每页显示的数据条数
        handleSizeChange(val) {
          this.listQuery.limit = val
          this.handleFilter()
        },
        // table表单下方的页码组件改变页面
        handleCurrentChange(val) {
          this.listQuery.page = val
          this.handleFilter()
        },
        transformDat(res) {
          const mapInfo = {
            jobNumberStr: '员工工号',
            deviceBarcode: '条码',
            scanProduceNo: '产品号',
            scanOrderType: '工单单别',
            scanWorkOrderNo: '工单单号',
            sopBarcode: 'sop号',
            scanTime: '扫码时间',
            standardManTime: '标准工时',
            planNo: '排产序号',
            isDelete: '状态',
            money: '金额',
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
        // 导出excel
        async hExportExcel() {
          this.loading = true
          let query = Object.assign({},this.listQuery)
          query.page = 1
          if(this.outputNum){
            query.limit = this.outputNum
          } else{
            query.limit = 10000
          }
          if(this.param.deviceBarcode){ query.deviceBarcode = this.param.deviceBarcode}
            if(this.param.jobNumber){ query.jobNumber = this.param.jobNumber}
            if(this.param.sectionNo){ query.sectionNo = this.param.sectionNo}
            if(this.param.scanWorkOrderNo){ query.scanWorkOrderNo = this.param.scanWorkOrderNo}
            if(this.param.scanOrderType){ query.scanOrderType = this.param.scanOrderType}
            if(this.param.scanProduceNo){ query.scanProduceNo = this.param.scanProduceNo}
            if(this.dateOptions) {
              if(this.dateOptions.length) {
                  query.strTime = this.dateOptions[0]
                  query.endTime = this.dateOptions[1]
              }
            }
          if(this.param.deviceBarcode){ query.deviceBarcode = this.param.deviceBarcode}
          if(this.param.jobNumber){ query.jobNumber = this.param.jobNumber}
          if(this.param.sectionNo){ query.sectionNo = this.param.sectionNo}
          if(this.param.money){ query.money = this.param.money}
          if(this.dateOptions) {
              if(this.dateOptions.length) {
                  query.strTime = this.dateOptions[0]
                  query.endTime = this.dateOptions[1]
              }
          }
          let arr = await findMachineScanInfo(query)
          if(arr.data.list.length) {
            arr.data.list.forEach(item=>{
              let jobNumberStr = []
              if(item.jobNumber) { jobNumberStr.push(item.jobNumber) }
              if(item.jobNumber2) { jobNumberStr.push(item.jobNumber2) }
              if(item.jobNumber3) { jobNumberStr.push(item.jobNumber3) }
              item.jobNumberStr = jobNumberStr.join(',')
            })
          }
          const { header, data } = this.transformDat(this.setSort(arr.data.list))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: 'ems车间员工扫码明细表', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let isshow = this.userInfo.account == 'lishali' || this.userInfo.roleId == 14 || this.userInfo.roleId == 44
          let arr1 = []
          newArr.forEach(item=>{
            let obj = {
              jobNumberStr: item.jobNumberStr,
              deviceBarcode: item.deviceBarcode,
              scanProduceNo: item.scanProduceNo,
              scanOrderType: item.scanOrderType,
              scanWorkOrderNo: item.scanWorkOrderNo,
              sopBarcode: item.sopBarcode,
              scanTime: item.scanTime,
              standardManTime: item.standardManTime,
              planNo: item.planNo,
              isDelete: item.isDelete == 0?'未删除':'已删除'
            }
            if(isshow) { obj.money = item.money?parseFloat(item.money).toFixed(3):0 }
            arr1.push(obj)
          })
          return arr1
        },
        cancelSubmit(){
            this.param = {
                deviceBarcode: '',                      //工序条码
                jobNumber: '',                           //员工工号
                date: '',                                //日期 
                sectionNo: ''                             //工段编号
            }
            this.listQuery.page = 1
            this.handleFilter()
        },
        setMonth() {
            var date = new Date()
            var year = date.getFullYear()
            var month = this.filterMonth(date.getMonth()+1)
            var day = this.filterMonth(date.getDate())
            return year + '-' + month + '-' + day
        },
        filterMonth(value) {
          if (value<10) {
            return '0' + value
          } else {
            return value
          }
        },
        //初始默认执行(重点)，返回日期格式YYYY-MM-DD HH:MM:SS
        getNowTime() {
            let dateTime = +new Date()+8*3600*1000
            const start = new Date(dateTime - 3600 * 1000 * 24 * 7)
                .toISOString()
                .replace('T', ' ')
                .split('.')[0]
                // .substring(0,10) //默认开始时间7天前
            const end = new Date(dateTime)
                .toISOString()
                .replace('T', ' ')
                .split('.')[0]
                // .substring(0,10)//默认结束时间当前时间
            console.log([start, end])
            return [start, end]
        },
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
    }
}
</script>

<style>

</style>